package org.groovyflow.db

import org.groovyflow.GroovyFlowContext

/**
 * @author Chuck Tassoni
 */
class DbHelp {
   	static def getDataSource(){
   		return GroovyFlowContext.get("defaultDataSource")
	}

	static def getTransaction(){
	   return new Transaction(getDataSource())
	}
	
	static def inTrx(clos){
		 getTransaction().exe(clos)
	}
	
	static def inTrx(clos,  dataSource){
		def usualDataSource = GroovyFlowContext.get("defaultDataSource")
		GroovyFlowContext.put("defaultDataSource", dataSource)
		try{
			inTrx(clos)
		}finally{
			GroovyFlowContext.put("defaultDataSource", usualDataSource)
		}
	}	
	
	static def mapsFromTrx(clos){
		def ret = inTrx(clos)
		return toMaps(ret)
	}

    /**
     * Turns a List of rows (each element a GroovyResultSet object) into a list of
     * maps.  It's also safe to pass in a single row, null, or a scalar.  A single row will
     * be returned as a single map, null as null, and a scalar as a scalar.
     */
    static def toMaps(rows){	
       if(rows == null) return null
       if(rows instanceof groovy.sql.GroovyRowResult) //Could be a single row
    	   return toMap(rows)
       if(! (rows instanceof List))//Could be a scalar value,  even an integer from an update statement
    	  return rows 
       def ret = []
       rows.each{ row ->
          ret << toMap(row)
       }
       return ret
    }
    
    static def toMap(row){
        def map = [:]
        row.each{ entry ->
            map.put(entry.key.toLowerCase(), entry.value)
        }
        return map
    }

}